package com.mtt.erp.common.utils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @Auther: SJZ    2907374717@qq.com
 * @Date: 2019/5/29 13:19
 * @Description: 腾讯云文件上传工具类
 */
@Component

public class QCloudOssUtils {

    private static String bucketName;

    private static String secretId;

    private static String secretKey;

    private static String regionName;

    @Value("${qCloud.bucketName}")
    public  void setBucketName(String bucketName) {
        QCloudOssUtils.bucketName = bucketName;
    }
    @Value("${qCloud.secretId}")
    public  void setSecretId(String secretId) {
        QCloudOssUtils.secretId = secretId;
    }
    @Value("${qCloud.secretKey}")
    public  void setSecretKey(String secretKey) {
        QCloudOssUtils.secretKey = secretKey;
    }
    @Value("${qCloud.regionName}")
    public  void setRegionName(String regionName) {
        QCloudOssUtils.regionName = regionName;
    }

    /**
     *上传前初始化信息，连接天腾讯云
     * @return
     */
    public static COSClient initCient(){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(regionName));
        COSClient cosClient = new COSClient(cred, clientConfig);
        return  cosClient;
    }

    /**
     * 上传到腾讯云
     * @param file
     * @param key
     * @return
     */
    public static PutObjectResult upload(File file,String key){
        PutObjectRequest putObjectRequest= new PutObjectRequest(bucketName,key,file);
        PutObjectResult putObjectResult=initCient().putObject(putObjectRequest);
        return putObjectResult;
    }


    /**
     * 删除某个对象文件
     * @param key
     */
    public static  void deleteObject(String key ){
        initCient().deleteObject(bucketName,key);
        shutDown();
    }
    /**
     * 关闭连接
     */
    public static void shutDown() {
        initCient().shutdown();
    }
}
